/**
 * Name:inputTags.js
 * Author:gene.jiang
 * E-mail:1013195469@qq.com
 * Website:http://www.jianggujin.com/
 * LICENSE:Apache v2 License
 * Description:标签输入框
 */
layui.define(['jquery', 'tool', 'geneconfig'], function(exports) {
    var $ = layui.jquery,
        _geneconfig_ = layui.geneconfig,
        _body_ = $('body'),
        _tool_ = layui.tool;

    layui.link(_geneconfig_.getModulePath() + '/css/inputtags.css');
    var InputTags = function(options) {
        this.__render(options);
    };

    InputTags.fn = InputTags.prototype;
    InputTags.fn.__render = function(options) {
        if(this._initialized) {
            layui.hint().error('InputTags已经初始化！');
            return;
        }
        options = options || {};
        if(!!options.elem) {
            this._container = $(options.elem);
            //存在配置的容器
            if(!this._container.length) {
                this._container = undefined;
            }
        }
        if(!this._container) {
            //选取默认容器
            this._container = _body_.find('input[gene-inputtags]');
        }
        if(!this._container || !this._container.length) {
            layui.hint().error('InputTags没有正常初始化！');
            return;
        }
        this._container = this._container.eq(0);

        var _that = this,
            _elem = this._container,
            _parent = _elem.parent(),
            _tagInput = $('<div class="tag-input"></div>'),
            _input = $('<input type="text" autocomplete="off">'),
            _tagInputId = _tool_.makeHashCode('tagInput'),
            _maxCount = options.maxCount || '-1',
            _separator = options.separator || ',';
        _parent.addClass("gene-inputtags").find('.tag-input').remove();
        _tagInput.attr("id", _tagInputId);
        _parent.append(_tagInput);
        _that._tagInput = _tagInput;
        _that._input = _input;
        _that._separator = _separator;

        _input.attr("placeholder", options.placeholder || '回车生成标签');
        _tagInput.append(_input);

        _tagInput.on('click', 'i[data-action=close]', function(e) {
            layui.stope(e);
            var $this = $(this);
            // 处理input 值
            var inputs = _elem.val().split(_separator);
            // 移除当前所选值
            _remove(inputs, $this.siblings('span').text());

            _elem.val(inputs.join(_separator));
            // 移除截元素
            $this.parent().remove();
        });

        _input.keypress(function(event) {
            var keynum = (event.keyCode ? event.keyCode : event.which);
            if(keynum == '13') {
                var _newVal = _input.val().trim();
                _input.val('');
                if(!_newVal) return false;
                var _val = _elem.val();
                if(!!$.trim(_val).length) {
                    var vals = _val.split(_separator);
                    if(_indexOf(vals, _newVal) > -1) return false;
                    _elem.val(vals.join(_separator));
                } else {
                    _elem.val(_newVal);
                }
                _addTag(_input, _newVal);
            }
        });
        _that._initialized = true;
        this.render();
        return _that;
    };

    function _addTag(_input, value) {
        _input.before([
            '<a href="javascript:;"><span>',
            value,
            '</span><i class="layui-icon" data-action="close">&#x1006;</i>',
            '</a>'
        ].join(''));
    }
    InputTags.fn.render = function() {
        if(!this._initialized) {
            return;
        }
        var _input = this._input,
            _elem = this._container,
            _separator = this._separator;
        var _vals = _elem.val();
        if(!!$.trim(_vals).length) {
            $.each(_vals.split(_separator), function(i, item) {
                _addTag(_input, item);
            });
        }
    };

    function _indexOf(arr, val) {
        for(var i = 0; i < arr.length; i++) {
            if(arr[i] == val) return i;
        }
        return -1;
    };

    function _remove(arr, val) {
        var index = _indexOf(arr, val);
        if(index > -1) {
            arr.splice(index, 1);
        }
    };

    function InputTagsExport() {}
    InputTagsExport.prototype.render = function(options) {
        return new InputTags(options);
    };
    exports('inputtags', new InputTagsExport());
});